<?php

namespace app\admin\controller\choi;

use app\common\model\RemindOrder as RemindOrderModel;
use app\common\controller\Backend;
use app\common\service\EasyWechatService;
use EasyWeChat\Factory;
use think\Db;
use app\admin\model\choi\CourseOrder as CourseOrderModel;
use app\admin\model\choi\Course as CourseModel;
use app\admin\model\choi\User as UserModel;
use app\admin\model\choi\UserMoneyLog as UserMoneyLogModel;

/**
 * 课程退款管理
 *
 * @icon fa fa-circle-o
 */
class CourseRefund extends Backend
{
    
    /**
     * CourseRefund模型对象
     * @var \app\admin\model\choi\CourseRefund
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\choi\CourseRefund;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['courseOrder', 'user'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['courseOrder', 'user'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 拒绝退款
     */
    public function refuse()
    {
        $id = $this->request->post('id');
        $refund = $this->model->find($id);
        if (!$refund) {
            $this->error('退款订单不存在');
        }
        if ($refund->status != 1) {
            $this->error('该申请已处理，无需再次操作');
        }
        $courseOrder = CourseOrderModel::find($refund->course_order_id);
        if (!$courseOrder) {
            $this->error('订单不存在');
        }
        $user = UserModel::find($refund->user_id);
        if (!$user) {
            $this->error('用户不存在');
        }
        Db::startTrans();
        try {
            $refund->status = 0;
            $refund->save();
            //更新订单
            CourseOrderModel::updateStatus($refund->course_order_id, 2);
            //更新课次
            CourseModel::rollbackStatus($refund->course_order_id);
            //订单提醒
            RemindOrderModel::add($courseOrder, 4);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        if (isset($e)) {
            $this->error($e->getMessage());
        }
        //订阅消息
        $this->subscribeData($courseOrder->order_no, $user->wxapp_openid, $refund, '申请退款被拒绝');
        $this->success('操作成功');
    }

    /**
     * 同意退款
     */
    public function agree()
    {
        $id = $this->request->post('id');
        $refund = $this->model->find($id);
        if (!$refund) {
            $this->error('退款订单不存在');
        }
        if ($refund->status != 1) {
            $this->error('该申请已处理，无需再次操作');
        }
        $courseOrder = CourseOrderModel::find($refund->course_order_id);
        if (!$courseOrder) {
            $this->error('课程订单不存在');
        }
        if ($courseOrder->status != 4) {
            $this->error('课程订单不在退款申请状态，无需处理');
        }
        $user = UserModel::find($refund->user_id);
        if (!$user) {
            $this->error('用户不存在');
        }

        Db::startTrans();
        try {
            //账户付款的
            if ($courseOrder->payment == 1) {
                //记录明细
                UserMoneyLogModel::add($user, $refund->total_fee, '课程退款');
                //退款到余额
                $user->setInc('money', $refund->total_fee);
            }
            //微信付款的
            if ($courseOrder->payment == 2) {
                //企业付款到零钱
                $this->balance($refund->order_no, $user->wxapp_openid, $refund->total_fee);
            }
            //更新退款状态
            $refund->status = 3;
            $refund->save();
            //更新订单状态
            CourseOrderModel::updateStatus($refund->course_order_id, 6);
            //更新课次状态
            CourseModel::updateStatus($refund->course_order_id);
            //订单提醒
            RemindOrderModel::add($courseOrder, 3);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        if (isset($e)) {
            $this->error($e->getMessage());
        }
        //订阅消息
        $this->subscribeData($courseOrder->order_no, $user->wxapp_openid, $refund, '已同意退款，请查收');
        $this->success('退款成功');
    }

    /**
     * 企业付款
     */
    private function balance($order_no, $openid, $amount)
    {
        $app = Factory::payment(config('wechat'));
        $res = $app->transfer->toBalance([
            'partner_trade_no' => $order_no, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $openid,
            'amount' => $amount * 100, // 企业付款金额，单位为分
            'check_name' => 'NO_CHECK', //不校验真实姓名
            'desc' => '课程退款', // 企业付款操作说明信息。必填
        ]);
        if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
            return true;
        } else {
            $this->error($res['return_msg']);
        }
    }

    /**
     * 订阅数据
     */
    private function subscribeData($orderNo, $openid, $refund, $text)
    {
        $data = [
            'template_id' => config('wechat.template')['refund_result'],
            'touser' => $openid,
            'page' => '',
            'data' => [
                'character_string1' => [
                    'value' => $orderNo
                ],
                'name3' => [
                    'value' => $text
                ],
                'amount4' => [
                    'value' => $refund['total_fee']
                ],
                'time5' => [
                    'value' => date('Y-m-d H:i')
                ],
                'thing6' => [
                    'value' => $refund['reason']
                ]
            ]
        ];
        $easywechatService = new EasyWechatService();
        return $easywechatService->send($data);
    }
}
